package com.hzsxy.bighomework.controller;

import ch.qos.logback.core.util.FileUtil;
import com.baidubce.BceClientException;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.doc.DocClient;
import com.baidubce.services.doc.model.*;
import com.hzsxy.bighomework.api.HomeworkView;
import com.hzsxy.bighomework.api.SubmitView;
import com.hzsxy.bighomework.entity.HomeworkDO;
import com.hzsxy.bighomework.entity.StudentDO;
import com.hzsxy.bighomework.entity.SubmitDO;
import com.hzsxy.bighomework.repository.HomeworkRepository;
import com.hzsxy.bighomework.repository.StudentRepository;
import com.hzsxy.bighomework.repository.SubmitRepository;
import com.hzsxy.bighomework.service.QuestionService;
import com.hzsxy.bighomework.util.DocFacade;
import com.hzsxy.bighomework.util.HttpFileUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import sun.nio.ch.IOUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class HomeworkController {

    @Autowired
    private SubmitRepository submitRepository;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private HomeworkRepository homeworkRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private DocClient docClient;

    @Autowired
    private BosClient bosClient;

    @PostMapping("/student/homework/submit")
    @ResponseBody
    public String submitHomework(HttpServletRequest request,HttpSession httpSession){
        try {
            MultipartFile multipartFile = ((StandardMultipartHttpServletRequest) request).getFile("file");
            int homeworkId=Integer.valueOf(request.getParameter("homeworkId"));
            HomeworkDO homeworkDO = homeworkRepository.findOne(homeworkId);
            Assert.isTrue(new Date().getTime()<homeworkDO.getEndTime().getTime(),"已截止，不可提交作业");
            StudentDO studentDO = (StudentDO) httpSession.getAttribute("info");
            Assert.isTrue(CollectionUtils.isEmpty(submitRepository.findByHomeworkIdAndStudentId(homeworkId,studentDO.getStudentId())),"不允许重复提交作业");
            String fileName = multipartFile.getOriginalFilename();
            int point = fileName.lastIndexOf(".");
            File tempFile = File.createTempFile(fileName.substring(0,point),fileName.substring(point));
            FileCopyUtils.copy(multipartFile.getInputStream(),new FileOutputStream(tempFile));
            String key = DigestUtils.md5DigestAsHex(new FileInputStream(tempFile));
            bosClient.putObject(DocFacade.BUCKET,key,tempFile);

            CreateDocumentFromBosRequest documentRequest = new CreateDocumentFromBosRequest();
            documentRequest.setBucket(DocFacade.BUCKET);
            documentRequest.setObject(key);
            documentRequest.setAccess("PUBLIC");
            documentRequest.setTitle(tempFile.getName());
            documentRequest.setFormat(fileName.substring(point+1));
            CreateDocumentFromBosResponse response = docClient.createDocumentFromBos(documentRequest);

            SubmitDO submitDO = new SubmitDO(homeworkId,studentDO.getStudentId(),response.getDocumentId());
            submitRepository.save(submitDO);
            return "succeeded";
        } catch (RuntimeException ex){
            ex.printStackTrace();
            return ex.getMessage();
        } catch (Exception ex){
            ex.printStackTrace();
            return "failed";
        }
    }

    @RequestMapping("/student/homework/all")
    public String getAllHomework(Model model,HttpSession httpSession){
        StudentDO studentDO= (StudentDO) httpSession.getAttribute("info");
        List<HomeworkView> homeworkViewList = questionService.getHomework(studentDO.getStudentId());
        model.addAttribute("views",homeworkViewList);
        return "student/student-homework-all";
    }

    @GetMapping("/student/homework/download")
    @ResponseBody
    public ReadDocumentResponse downloadHomework(@RequestParam int homeworkId, HttpSession httpSession){
        StudentDO studentDO = (StudentDO) httpSession.getAttribute("info");
        List<SubmitDO> submitDOList = submitRepository.findByHomeworkIdAndStudentId(homeworkId,studentDO.getStudentId());
        Assert.isTrue(!CollectionUtils.isEmpty(submitDOList),"找不到该作业");
        String documentId = submitDOList.get(0).getAnswer();
        return docClient.readDocument(documentId);
    }

    @RequestMapping("/teacher/homework/getSubmits")
    private String getSubmits(Model model,@RequestParam int questionId){
        List<HomeworkDO> homeworkDOList = homeworkRepository.findByQuestionId(questionId);
        List<SubmitView> submitViewList = new ArrayList<>();
        homeworkDOList.forEach(it -> {
            List<SubmitDO> submitDOList = submitRepository.findByHomeworkId(it.getId());
            List<SubmitView> tempView = submitDOList.stream().map( submit -> {
                SubmitView view = new SubmitView();
                view.setId(submit.getId());
                view.setStudentId(submit.getStudentId());
                view.setSubmitTime(submit.getSubmitTime().toString());
                view.setStudentName(studentRepository.findOne(submit.getStudentId()).getName());
                return view;
            }).collect(Collectors.toList());
            submitViewList.addAll(tempView);
        });
        model.addAttribute("views",submitViewList);
        return "teacher/homework-submits";
    }


    @GetMapping("/teacher/homework/download")
    @ResponseBody
    public ReadDocumentResponse downloadSubmit(@RequestParam int submitId, HttpSession httpSession,HttpServletResponse response){
        SubmitDO submitDO = submitRepository.findOne(submitId);
        String documentId = submitDO.getAnswer();
        return docClient.readDocument(documentId);
    }


//    @GetMapping("/teacher/homework/download")
//    @ResponseBody
//    public String downloadSubmit(@RequestParam int sumbitId, HttpSession httpSession,HttpServletResponse response){
//        try{
//            SubmitDO submitDO = submitRepository.findOne(sumbitId);
//            String filePath = submitDO.getAnswer();
//            File file = new File(filePath);
//            Assert.isTrue(file.exists(),"由于系统重新部署导致作业文件丢失，请清除数据库数据后重新上传");
//            HttpFileUtil.downloadFile(file,response);
//            return "succeeded";
//        } catch (RuntimeException ex){
//            return ex.getMessage();
//        } catch (Exception ex){
//            return "failed";
//        }
//    }
}
